﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using NIF.MobileActors.Core;
namespace NIF.MobileActors.Hosts
{
    internal class HostLocalFacade:IHostLocal 
    {
        public void Start()
        {
            //设置CurrentDomain的assembly resolver 
            //AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(
            //    (object sender, ResolveEventArgs args) =>
            //    {
            //        AssemblyName asmName = new AssemblyName(args.Name);
            //        byte[] bytes = AssemblyManager.Instance.GetRawAssembly(asmName.FullName);
            //        if (bytes == null)
            //        {
            //            return Assembly.Load(args.Name);
            //        }
                    
            //        System.Diagnostics.Debug.Assert(bytes != null && bytes.Length > 0);
            //        Assembly xAsm = Assembly.Load(bytes);  //装载程序集
            //        return xAsm;
            //    });
        }

        public ActorProxy<T> CreateLocalActor<T>(Type aType)
        {
            //return ActorManager.Instance.CreateLocalActor(aType);
            return new ActorProxy<T>(ActorManager.Instance.CreateLocalActor(aType) as ActorBase<T>);
        }

        public byte[] RetrieveAssemblyBytes(string asmName)
        {
            return AssemblyManager.Instance.GetRawAssembly(asmName);
        }

        public ActorProxy<T> GetActorProxy<T>(ActorID id)
        {
            if (!(ActorManager.Instance.GetActor(id) is ActorBase<T>))
                return null;
            return new ActorProxy<T>(ActorManager.Instance.GetActor(id) as ActorBase<T>);
        }

        public ActorProxy<T>[] GetActorProxies<T>()
        {
            ActorBase<T>[] actors = ActorManager.Instance.GetActors<T>();
            ActorProxy<T>[] proxies = new ActorProxy<T>[actors.Length];
            int i = 0;
            foreach (ActorBase<T> actor in actors)
                proxies[i++] = new ActorProxy<T>(actor);
            return proxies;
        }

        public IActor Retract(ActorID id)
        {
            throw new NotImplementedException();
        }

        public ActorID Clone(IActor actor, string actorTypeName)
        {
            throw new NotImplementedException();
        }
    }
}
